package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiDuMapProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Autowired
    private BaiDuMapProperties baiDuMapProperties;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @Return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();//获取当前帐号id
        //1,首先要进行事务异常处理，判断地址与购物车是否为空,若为空抛出异常
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //判断配送距离是否超过5公里
        try {
            checkDeliveryDistance(shopAddress, addressBook.getDetail());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //2.向订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);//将orderSubmitDTO属性拷贝到orders中
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(Orders.UN_PAID);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setOrderTime(LocalDateTime.now());
        orders.setUserId(userId);
        orderMapper.insert(orders);
        //3.向订单明细表中插入n条数据
        OrderDetail orderDetail = new OrderDetail();
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }
        orderDetailMapper.insertBatch(list);
        //4.清空购物车数据
        shoppingCartMapper.cleanShoppingCart(userId);
        //5.返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
       /* //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");


        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 替代微信支付成功后的数据库订单状态更新，直接在这里更新了
        // 根据订单号查询当前用户的该订单
        Orders ordersDB = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());

        orderMapper.update(orders);
        //通过websocket推送消息给客户端 type orderId content
        HashMap map = new HashMap();
        map.put("type", 1);//1代表来单提醒 2代表客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + ordersDB.getNumber());
        //将map转为json
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //通过websocket推送消息给客户端 type orderId content
        Map map = new HashMap();
        map.put("type", 1);//1代表来单提醒 2代表客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + ordersDB.getNumber());
        //将map转为json
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @Return ordersDTO
     */
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 查看历史订单
     */
    public PageResult page(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> pages = orderMapper.page(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if (!pages.isEmpty()) {
            for (Orders orders : pages) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orders.getId());
                orderVO.setOrderDetailList(byOrderId);
                list.add(orderVO);
            }
        }
        return new PageResult(pages.getTotal(), list);
    }

    /**
     * 取消订单
     */
    public void cancelOrder(Long id) {
        Orders orders = new Orders();
        orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Transactional
    public void repetition(Long id) {
        // 根据订单ID获取所有订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 初始化购物车列表，用于存储转换后的购物车对象
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        // 遍历订单详情列表
        for (OrderDetail detail : orderDetailList) {
            // 创建一个新的购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            // 设置当前用户ID
            shoppingCart.setUserId(BaseContext.getCurrentId());
            // 将订单详情的属性复制到购物车对象中
            BeanUtils.copyProperties(detail, shoppingCart);
            // 设置创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 将购物车对象添加到列表中
            shoppingCartList.add(shoppingCart);
        }
        // 批量插入购物车对象到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
    * 管理端服务
    * 管理端服务
    * 管理端服务管理端服务
    * 管理端服务管理端服务
    * 管理端服务管理端服务
    * 管理端服务管理端服务
    * 管理端服务管理端服务
    * 管理端服务管理端服务
    * 管理端服务管理端服务
    *
    * 管理端服务管理端服务
    *
    * 管理端服务管理端服务管理端服务
    * */



   /**
    * 管理端订单搜索
    * */
    public PageResult searchOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        //利用PageHelper插件进行分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage=orderMapper.page(ordersPageQueryDTO);
        List<OrderVO> orderVOList=new ArrayList<>();
        for (Orders orders : ordersPage) {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVOList.add(orderVO);
        }
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 管理端查看各个状态的订单数量统计
     * */
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

           orderStatisticsVO.setToBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED));
           orderStatisticsVO.setConfirmed(orderMapper.countStatus(Orders.CONFIRMED));
           orderStatisticsVO.setDeliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /**
     *
     * 管理端接单服务
     * */
    public void confirm(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     *
     * 管理端派送单服务
     * */
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 管理端完成订单服务
     * */
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 管理端拒绝订单
     * */
    public void rejectionRiderOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * */
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
      //判断订单是否为空，为空：抛出异常
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
       Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 商家管理端取消订单
     * */
    public void cancelRiderOrder(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        Integer payStatus = orders.getPayStatus();
        if (payStatus == Orders.PAID) {
            orders.setStatus(Orders.CANCELLED);
        }
        orders.setRejectionReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    /**
     * 计算商家与客户的距离
     * @param shopAddress 商家地址
     * @param customerAddress 客户地址
     * @return 距离（单位：米）
     * @throws Exception 如果距离大于5000米，抛出异常
     */
    private int calculateDistance(String shopAddress, String customerAddress) throws Exception {
        // 百度地图API URL
        String url = "https://api.map.baidu.com/directionlite/v1/driving";
        // 构造请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("origin", shopAddress);
        paramMap.put("destination", customerAddress);
        paramMap.put("ak", baiDuMapProperties.getAk()); // 使用配置中的AK

        // 发送GET请求调用百度地图API
        String response = HttpClientUtil.doGet(url, paramMap);

        // 解析API返回的JSON数据
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("status") != 0) {
            throw new OrderBusinessException("百度地图API调用失败：" + jsonObject.getString("message"));
        }

        // 获取距离（单位：米）
        int distance = jsonObject.getJSONObject("result")
                .getJSONArray("routes")
                .getJSONObject(0)
                .getInteger("distance");

        return distance;
    }
    /**
     * 检查商家与客户的距离是否在可配送范围内
     * @param shopAddress 商家地址
     * @param customerAddress 客户地址
     * @throws Exception 如果距离大于5000米，抛出异常
     */
    public void checkDeliveryDistance(String shopAddress, String customerAddress) throws Exception {
        int distance = calculateDistance(shopAddress, customerAddress);
        if (distance > 5000) {
            throw new OrderBusinessException(MessageConstant.DELIVERY_DISTANCE_TOO_FAR);
        }
    }
}